/**
 * JAVACC DEMO 1.0
 * @copy right iussoft company All rights reserved.
 * @Package com.iussoft.portal.servlet
 */
package com.apache.portal.contorller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;

import com.apache.api.vo.ResultMsg;
import com.apache.passport.common.DesUtils;
import com.apache.passport.common.PassportHelper;
import com.apache.portal.common.enums.UserMethodEnum;
import com.apache.portal.common.util.PortalPubFactory;
import com.apache.portal.service.SendEmailServiceImpl;
import com.apache.tools.StrUtil;
import com.apache.uct.common.ToolsUtil;

/**
 * description:  uct子系统sevlet
 * @author Hou Dayu 创建时间：2016-8-22
 */
@SuppressWarnings("serial")
public class UserServlet extends BaseHttpServlet {
	private Logger log = Logger.getLogger(UserServlet.class);

	/**
	 * TODO 简单描述该方法的实现功能（可选）.  
	 * @see com.iussoft.portal.servlet.BaseHttpServlet#doInvoke(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	protected void doInvoke(HttpServletRequest request, HttpServletResponse response) throws ServletException,
			IOException {
		String doCode = request.getParameter("doCode");
		String result = "";
		Map<String, String> params = this.getParameterMap(request);
		ResultMsg msg = null;
		switch (UserMethodEnum.getName(doCode)) {
		case loginNoCode://不需要验证码的登录
			msg = (ResultMsg) PortalPubFactory.getInstance().getPlugin("uct").doInvoke(request, response, params);
			if (null != msg) {
				result = JSONObject.fromObject(msg).toString();
			}
			break;
		case login:
			this.setLoginUser(request);
			if (ToolsUtil.isEmpty(this.getSessionUser(request))) {
				msg = checkRandCode(request, params);
				if (null != msg) {
					result = JSONObject.fromObject(msg).toString();
				} else {
					msg = (ResultMsg) PortalPubFactory.getInstance().getPlugin("uct")
							.doInvoke(request, response, params);
					if (null != msg) {
						result = JSONObject.fromObject(msg).toString();
					}
				}
			} else {
				msg = new ResultMsg("T", "登陆成功");
				result = JSONObject.fromObject(msg).toString();
			}
			break;
		case regUser:
			msg = checkRandCode(request, params);
			if (null != msg) {
				result = JSONObject.fromObject(msg).toString();
			} else {
				msg = (ResultMsg) PortalPubFactory.getInstance().getPlugin("uct").doInvoke(request, response, params);
				if (null != msg) {
					result = JSONObject.fromObject(msg).toString();
				}
			}
			break;
		case regUserMailCode://邮箱验证码方式的注册
			String mail_start = ToolsUtil.getInstance().getValueByKey("mail_start");
			if ("T".equals(mail_start)) {//开启发邮件才校验
				msg = checkEmailCode(request, params);
				if ("T".equals(msg.getFlag())) {
					msg = (ResultMsg) PortalPubFactory.getInstance().getPlugin("uct")
							.doInvoke(request, response, params);
				}
			} else {
				//未开启发邮件，直接注册
				msg = (ResultMsg) PortalPubFactory.getInstance().getPlugin("uct").doInvoke(request, response, params);
			}
			if (null != msg) {
				result = JSONObject.fromObject(msg).toString();
			}
			break;
		case editUser:
			msg = (ResultMsg) PortalPubFactory.getInstance().getPlugin("uct").doInvoke(request, response, params);
			if (null != msg) {
				result = JSONObject.fromObject(msg).toString();
			}
			break;
		case FindPwd:
			msg = checkRandCode(request, params);
			if (null != msg) {
				result = JSONObject.fromObject(msg).toString();
			} else {
				msg = (ResultMsg) PortalPubFactory.getInstance().getPlugin("uct").doInvoke(request, response, params);
				if (null != msg) {
					result = JSONObject.fromObject(msg).toString();
				}
			}
			break;
		case editPwd:
			msg = checkRandCode(request, params);
			if (null != msg) {
				result = JSONObject.fromObject(msg).toString();
			} else {
				msg = (ResultMsg) PortalPubFactory.getInstance().getPlugin("uct").doInvoke(request, response, params);
				if (null != msg) {
					result = JSONObject.fromObject(msg).toString();
				}
			}
			break;
		case SetUserPwd:
			setUserPwd(request, response, params);
			break;
		case logout:
			msg = (ResultMsg) PortalPubFactory.getInstance().getPlugin("uct").doInvoke(request, response, params);
			if (null != msg) {
				result = JSONObject.fromObject(msg).toString();
			}
			break;
		case sendPwd://发送注册验证码
			msg = sendRegCodeNumber(request, response, params);
			if (null != msg) {
				result = JSONObject.fromObject(msg).toString();
			}
			break;
		case toIndex:
			gotoIndex(request, response);
			break;
		}
		this.outputJson(result, response);
	}

	/**
	 * 发布注册验证码
	 */
	private ResultMsg sendRegCodeNumber(HttpServletRequest request, HttpServletResponse response,
			Map<String, String> params) {
		ResultMsg msg = new ResultMsg("F", "验证码发送失败");
		long sendTime = System.currentTimeMillis();
		String msgType = StrUtil.doNull(request.getParameter("sendType"), "mail");
		String mail_start = ToolsUtil.getInstance().getValueByKey("mail_start");
		if (!"T".equals(mail_start)) {
			msg = new ResultMsg("F", "服务端已停用发送邮件通知业务");
			return msg;
		}
		if ("mail".equalsIgnoreCase(msgType)) {
			String times = StrUtil.doNull(String.valueOf(request.getSession().getAttribute("sendTime")), "0");
			long sendTimeUp = Long.valueOf(times);
			long count = 15 * 60 * 1000;
			if (sendTime - sendTimeUp > count) {
				String codeNumber = PortalPubFactory.getRandomNumber(6);
				Map<String, String> sendMap = new HashMap<String, String>();
				String userEmail = params.get("email");
				log.info("正在给[" + userEmail + "]发送邮箱验证码...");
				sendMap.put("userEmail", userEmail);
				sendMap.put("content", codeNumber);
				sendMap.put("title", ToolsUtil.getInstance().getValueByKey("mail.title.code.number"));
				sendMap.put("tempName", "mailCodeNumber.inc");//指定使用的模板
				sendMap.put("emailPwd", ToolsUtil.getInstance().getValueByKey("mail_pwd"));
				sendMap.put("host", ToolsUtil.getInstance().getValueByKey("mail_host"));
				sendMap.put("from", ToolsUtil.getInstance().getValueByKey("mail_user"));
				sendMap.put("protocol", ToolsUtil.getInstance().getValueByKey("mail.protocol"));
				sendMap.put("platformName", ToolsUtil.getInstance().getValueByKey("mail.platform.name"));
				log.info("发送内容：" + sendMap);
				PortalPubFactory.getInstance().setSends("findPwdEmail", new SendEmailServiceImpl());
				//发送邮件
				boolean mark = PortalPubFactory.getInstance().getSends("findPwdEmail").sendMessage(sendMap);
				log.info("发送结果：" + mark);
				if (mark) {
					msg = new ResultMsg("T", "验证码发送成功，请登录您的邮箱获取验证码");
					request.getSession().setAttribute("mailCode", codeNumber);
					request.getSession().setAttribute("sendTime", sendTime);
				}
			} else {
				msg = new ResultMsg("F", "验证码已发送成功，请登录您的邮箱获取验证码");
			}
		}
		return msg;
	}

	/**
	 * description:  验证邮箱验证码
	 */
	private ResultMsg checkEmailCode(HttpServletRequest request, Map<String, String> params) {
		ResultMsg msg = new ResultMsg("T", "验证成功");
		if ((StrUtil.isNull(params.get("emailCode")))) {
			msg = new ResultMsg("F", "验证码不能为空");
			return msg;
		}
		String randCode = String.valueOf(request.getSession().getAttribute("mailCode"));
		if (!params.get("emailCode").equals(randCode)) {
			msg = new ResultMsg("F", "验证码错误");
			return msg;
		}
		return msg;
	}

	/**
	 * description:  验证验证码
	 */
	private ResultMsg checkRandCode(HttpServletRequest request, Map<String, String> params) {
		ResultMsg msg = null;
		if ((StrUtil.isNull(params.get("rand")))) {
			msg = new ResultMsg("F", "验证码不能为空");
			return msg;
		}
		String randCode = String.valueOf(request.getSession().getAttribute("randCode"));
		if (!params.get("rand").equals(randCode)) {
			msg = new ResultMsg("F", "验证码错误");
			return msg;
		}
		return msg;
	}

	/**
	 * description:  邮箱链接验证
	 */
	private void setUserPwd(HttpServletRequest request, HttpServletResponse response, Map<String, String> params)
			throws ServletException, IOException {
		if (ToolsUtil.isNull(params.get("rand"))) {
			response.sendRedirect(request.getContextPath());
			return;
		}
		long toDay = System.currentTimeMillis();
		String encryKey = params.get("rand");//发送时间
		long randL = Long.valueOf(encryKey);
		long cha = toDay - randL;
		if (cha <= 24 * 3600 * 1000L && cha > 0) {
			String email1 = DesUtils.getInstance().decrypt(params.get("e"));
			String userEname = DesUtils.getInstance().decrypt(params.get("u"));
			request.setAttribute("userEname", userEname);
			request.setAttribute("userEmail", email1);
		} else {
			response.sendRedirect(request.getContextPath());
			return;
		}
		request.getRequestDispatcher("doSendPage?toPage=res002").forward(request, response);
	}

	/**
	 * description:  登录成功后跳转页面
	 */
	private void gotoIndex(HttpServletRequest request, HttpServletResponse response) throws ServletException,
			IOException {
		String path = request.getContextPath();
		String csetUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path;
		//要跳转到哪个url
		String gotoURL = request.getParameter("go");
		if (StrUtil.isNull(gotoURL)) {
			gotoURL = csetUrl;
		} else {
			if (gotoURL.startsWith(path)) {
				gotoURL = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
						+ gotoURL;
			}
		}
		//自定义登录页面
		String login_url = ToolsUtil.getInstance().getValueByKey("uct_server");
		//获取系统名称
		String tokenId = String.valueOf(request.getSession().getAttribute("tokenId"));
		String reqParams = "";
		if ("T".equals(ToolsUtil.getInstance().getValueByKey("is_url_params"))) {
			reqParams = PassportHelper.getInstance().getReqParams(request, "doCode,go");
			reqParams = PassportHelper.getInstance().isNov(reqParams, reqParams, "?" + reqParams);
		}
		ArrayList<String> lst = new ArrayList<String>();
		StringBuffer tokenUrl = new StringBuffer();
		lst.add(login_url);
		lst.add(tokenId);
		lst.add(gotoURL + reqParams);
		lst.add("iussoft");
		lst.add(csetUrl);
		Collections.sort(lst);
		String sha1Rtn = PassportHelper.getInstance().SHA1(lst);
		//是否使用统一登录系统登录 T/F
		String login_pass = ToolsUtil.getInstance().getValueByKey("login.pass");
		if ("T".equals(login_pass)) {
			//如果cookie为空,则跳转到登录页面
			tokenUrl.append(login_url);
			tokenUrl.append("?");
			tokenUrl.append("ptlang=" + sha1Rtn);
			tokenUrl.append("&");
			tokenUrl.append("tokenId=" + tokenId);//设置远程cookie
			tokenUrl.append("&");
			tokenUrl.append("go=" + gotoURL + reqParams);
			tokenUrl.append("&");
			tokenUrl.append("cset=" + csetUrl);
		} else {
			tokenUrl.append(login_url);
		}
		response.sendRedirect(tokenUrl.toString());
	}
}
